package Game 
{
	import flash.display.Sprite;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	/**
	 * ...
	 * @author Vijay Ramani
	 * 
	 * 
	 * Responsibilities of this class
	 *  - Handle movement of all objects as per movement depth ratios
	 *  - Clipping of all objects from screen view
	 * 
	 */
	public class GameCamera 
	{
		private var renderObjs:Array = new Array();
		
		private var pos:Point = null;
		private var nextPos:Point = null;
		private var diffPos:Point = null;
		private var viewport:Rectangle = null;
		
		public function GameCamera(_viewport:Rectangle = null) 
		{
			if (_viewport) viewport = _viewport;
			else viewport = new Rectangle(0, 0, 640, 480);
			
			pos = new Point();
			nextPos = new Point();
			diffPos = new Point();
		}
		public function AddToRenderList(_obj:GameEntity, _depth:Number = 1):void
		{
			renderObjs.push( { entity:_obj, depth:_depth } );
		}
		
		public function Remove(_obj:GameEntity):void
		{
			for (var i:uint = 0; i < renderObjs.length; i++)
			{
				if (renderObjs[i].entity == _obj)
				{
					renderObjs.splice(i, 1);
					break;
				}
			}
		}
		
		public function Update():void
		{
			if (!nextPos.equals(pos))
			{
				diffPos = nextPos.subtract(pos);
				diffPos.x = diffPos.x / 10;
				diffPos.y = diffPos.y / 10;
				pos = pos.add(diffPos);
			}
			
			var _s:GameEntity = null;
			var _d:Number = 1;
			for (var i:uint = 0; i < renderObjs.length; i++)
			{
				_s = renderObjs[i].entity;
				_d = renderObjs[i].depth;
				if (!_s)
				{
					renderObjs.splice(i, 1);
					i--;
					continue;
				}
				else
				{
					_s.x = (_s.Pos.x - pos.x) * _d;
					_s.y = (_s.Pos.y - pos.y) * _d;
					_s.visible = false;
					
					if (_s.x > viewport.right) continue;
					if (_s.y > viewport.bottom) continue;
					if (_s.x + _s.width < viewport.left) continue;
					if (_s.y + _s.height < viewport.top) continue;
					
					_s.visible = true;
				}
			}
		}
		
		public function MoveTo(_x:int, _y:int):void
		{
			nextPos.x = _x;
			nextPos.y = _y;
		}
		
		public function set Pos(_value:Point):void
		{
			nextPos = _value;
		}
		public function get Pos():Point
		{
			return nextPos;
		}
		
		public function set Viewport(_value:Rectangle):void
		{
			viewport = _value;
		}
		public function get Viewport():Rectangle
		{
			return viewport;
		}
	}

}